<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import dayjs from 'dayjs';
import request from '../utils/request.js';

// 导入API
import {
  getSystemKnowledgeBasesService,
  getUserKnowledgeBasesService,
  getSelectedKbService,
  selectKbService,
  createKnowledgeBaseService,
  uploadFileToKbService,
  getKbFilesService,
  deleteKbFileService,
  deleteKnowledgeBaseService,
  deselectKbService,
  createSystemKnowledgeBaseService,
  uploadFileToSystemKbService,
  deleteSystemKnowledgeBaseService,
  deleteSystemKbFileService,
  getFilesBySystemKbIdService
} from '../api/Knowledge.js';

// 导入图标
import { Book, Trash2, File } from 'lucide-vue-next';

// 路由与基础状态
const route = useRoute();
const router = useRouter();
const numericId = parseInt(route.params.robotId);

// 工具方法
const formatDate = (dateString) => {
  if (!dateString) return '';
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
};

// 提示框状态
const showToast = ref(false);
const toastMessage = ref('');
const toastType = ref('success');
const showToastMessage = (message, type = 'success') => {
  toastMessage.value = message;
  toastType.value = type;
  showToast.value = true;
  setTimeout(() => showToast.value = false, 3000);
};

// 核心数据状态
const systemKnowledgeBases = ref([]);
const userKnowledgeBases = ref([]);
const selectedKb = ref(null);
const loading = ref(true);
const error = ref('');

// 模态框与表单状态
const isCreateModalOpen = ref(false);
const isFileListModalOpen = ref(false);
const isUploadFileModalOpen = ref(false);
const kbName = ref('');
const kbDescription = ref('');
const selectedFilesToUpload = ref([]);
const fileToUpload = ref(null);
const uploadFileInput = ref(null);
const createFileInput = ref(null);
const uploading = ref(false);
const progress = ref(0);

// 管理员相关状态
const { email, isAdmin } = getUserInfo();
const isCreateSystemKbModalOpen = ref(false);
const isSystemFileListModalOpen = ref(false);
const isSystemUploadFileModalOpen = ref(false);
const selectedSystemKb = ref(null);

/**
 * 获取用户信息（包含管理员判断）
 */
function getUserInfo() {
  const email = sessionStorage.getItem('user') || '';
  return {
    email,
    isAdmin: email === '3186965058@qq.com'
  };
}

/**
 * 页面初始化：并行请求系统知识库/个人知识库/已选知识库
 */
const fetchInitialData = async () => {
  // 参数校验
  if (!email || isNaN(numericId)) {
    error.value = isNaN(numericId) ? '机器人ID无效' : '用户信息不完整，请重新登录';
    loading.value = false;
    return;
  }

  try {
    loading.value = true;
    // 并行请求
    const [systemKbData, userKbData, selectedKbData] = await Promise.all([
      getSystemKnowledgeBasesService(),
      getUserKnowledgeBasesService(email),
      getSelectedKbService(numericId)
    ]);

    // 处理系统知识库
    systemKnowledgeBases.value = systemKbData.map(kb => ({
      ...kb,
      docCount: kb.doc_count || 0,
      files: kb.files || []
    }));
    console.log('系统知识库:', systemKnowledgeBases.value);

    // 处理个人知识库
    userKnowledgeBases.value = userKbData || [];
    for (const kb of userKnowledgeBases.value) {
      const files = await getKbFilesService(kb.id);
      kb.files = files;
      kb.docCount = kb.doc_count;
    }
    console.log('个人知识库:', userKnowledgeBases.value);

    // 处理已选知识库
    if (selectedKbData && selectedKbData.knowledge_base_id) {
      if (selectedKbData.from === 'system') {
        const matched = systemKnowledgeBases.value.find(kb => kb.id === selectedKbData.knowledge_base_id);
        if (matched) selectedKb.value = { ...matched, isUserKb: false };
      } else if (selectedKbData.from === 'personal') {
        const matched = userKnowledgeBases.value.find(kb => kb.id === selectedKbData.knowledge_base_id);
        if (matched) selectedKb.value = { ...matched, isUserKb: true };
      }
    }
  } catch (err) {
    error.value = err.message || '数据加载失败，请刷新页面重试';
    showToastMessage(error.value, 'error');
    console.error('初始化错误:', err);
  } finally {
    loading.value = false;
  }
};

/**
 * 选择知识库关联机器人
 */
const selectKnowledgeBase = async (kb, isUserKb = false) => {
  if (isNaN(numericId)) {
    showToastMessage('机器人ID无效，无法保存选择', 'error');
    return;
  }

  try {
    await selectKbService({
      robotId: numericId,
      knowledgeBaseId: kb.id,
      isSystem: !isUserKb
    });
    selectedKb.value = { ...kb, isUserKb };
    showToastMessage('选择知识库成功');
  } catch (err) {
    showToastMessage(`选择失败: ${err.message}`, 'error');
    console.error('选择知识库错误:', err);
  }
};

/**
 * 打开/关闭模态框
 */
const openCreateModal = () => {
  isCreateModalOpen.value = true;
  kbName.value = '';
  kbDescription.value = '';
  selectedFilesToUpload.value = [];
  if (createFileInput.value) createFileInput.value.value = '';
};

const openFileListModal = async (kb) => {
  try {
    const files = await getKbFilesService(kb.id);
    kb.files = files;
    kb.docCount = files.length;
    selectedKb.value = { ...kb, isUserKb: true };
    isFileListModalOpen.value = true;
  } catch (err) {
    showToastMessage(`获取文件列表失败: ${err.message}`, 'error');
  }
};

const openUploadFileModal = () => {
  if (selectedKb.value?.isUserKb) {
    isUploadFileModalOpen.value = true;
    fileToUpload.value = null;
    if (uploadFileInput.value) uploadFileInput.value.value = '';
  }
};

const closeCreateModal = () => isCreateModalOpen.value = false;
const closeFileListModal = () => isFileListModalOpen.value = false;
const closeUploadFileModal = () => isUploadFileModalOpen.value = false;

// 管理员模态框控制
const openCreateSystemKbModal = () => {
  isCreateSystemKbModalOpen.value = true;
  kbName.value = '';
  kbDescription.value = '';
  selectedFilesToUpload.value = [];
  if (createFileInput.value) createFileInput.value.value = '';
};

const closeCreateSystemKbModal = () => isCreateSystemKbModalOpen.value = false;

const openSystemFileListModal = async (kb) => {
  try {
    const email = sessionStorage.getItem('user'); 
    const files = await getFilesBySystemKbIdService(kb.id,email);
    selectedSystemKb.value = {
      ...kb,
      files: files.map(file => ({
        id: file.id,
        name: file.name,
        size: file.size,
        uploadedAt: file.created_at,
        type: file.type
      }))
    };
    isSystemFileListModalOpen.value = true;
  } catch (err) {
    showToastMessage(`获取系统知识库文件列表失败: ${err.message}`, 'error');
  }
};

const openSystemUploadFileModal = () => {
  if (selectedSystemKb.value) {
    isSystemUploadFileModalOpen.value = true;
    fileToUpload.value = null;
    if (uploadFileInput.value) uploadFileInput.value.value = '';
  }
};

const closeSystemFileListModal = () => isSystemFileListModalOpen.value = false;
const closeSystemUploadFileModal = () => isSystemUploadFileModalOpen.value = false;

const closeModalOnOutside = (e, modalType) => {
  if (e.target === e.currentTarget) {
    if (modalType === 'create') closeCreateModal();
    else if (modalType === 'fileList') closeFileListModal();
    else if (modalType === 'uploadFile') closeUploadFileModal();
    else if (modalType === 'createSystem') closeCreateSystemKbModal();
    else if (modalType === 'systemFileList') closeSystemFileListModal();
    else if (modalType === 'systemUploadFile') closeSystemUploadFileModal();
  }
};

/**
 * 文件选择处理
 */
const handleCreateFileSelection = (e) => {
  const files = e.target.files;
  if (files.length > 0) selectedFilesToUpload.value = Array.from(files);
};

const handleUploadFileSelection = (e) => {
  const files = e.target.files;
  if (files.length > 0) fileToUpload.value = files[0];
};

/**
 * 表单验证
 */
const isCreateFormValid = computed(() => {
  return kbName.value.trim() !== '' && kbDescription.value.trim() !== '' && selectedFilesToUpload.value.length > 0;
});

const isUploadFormValid = computed(() => {
  return fileToUpload.value !== null;
});

/**
 * 创建个人知识库
 */
const handleCreateKb = async () => {
  if (!email) {
    showToastMessage('用户未登录，无法创建知识库', 'error');
    return;
  }
  if (!isCreateFormValid.value) {
    showToastMessage('请完善知识库名称、描述并选择文件', 'error');
    return;
  }

  uploading.value = true;
  progress.value = 0;

  try {
    const formData = new FormData();
    formData.append('name', kbName.value);
    formData.append('description', kbDescription.value);
    formData.append('email', email);
    selectedFilesToUpload.value.forEach(file => formData.append('files', file));

    const newKb = await createKnowledgeBaseService(formData, (e) => {
      if (e.lengthComputable) {
        progress.value = Math.round((e.loaded / e.total) * 100);
      }
    });

    const files = await getKbFilesService(newKb.id);
    newKb.files = files;
    newKb.docCount = newKb.doc_count;
    userKnowledgeBases.value.push(newKb);

    await selectKnowledgeBase(newKb, true);
    showToastMessage(`知识库创建成功，已上传 ${selectedFilesToUpload.value.length} 个文件`);
    closeCreateModal();
  } catch (err) {
    showToastMessage(`创建失败: ${err.message}`, 'error');
    console.error('创建知识库错误:', err);
  } finally {
    uploading.value = false;
    progress.value = 0;
  }
};

/**
 * 管理员创建系统知识库
 */
const handleCreateSystemKb = async () => {
  if (!isAdmin) {
    showToastMessage('非管理员无权限操作', 'error');
    return;
  }
  if (!isCreateFormValid.value) {
    showToastMessage('请完善系统知识库名称、描述并选择文件', 'error');
    return;
  }

  uploading.value = true;
  progress.value = 0;

  try {
    const formData = new FormData();
    formData.append('name', kbName.value);
    formData.append('description', kbDescription.value);
    formData.append('email', email);
    selectedFilesToUpload.value.forEach(file => formData.append('files', file));

    const newSystemKb = await createSystemKnowledgeBaseService(formData, (e) => {
      if (e.lengthComputable) progress.value = Math.round((e.loaded / e.total) * 100);
    });

    systemKnowledgeBases.value.push({
      ...newSystemKb,
      docCount: newSystemKb.doc_count || 0,
      files: newSystemKb.files || []
    });
    showToastMessage(`系统知识库创建成功，已上传 ${selectedFilesToUpload.value.length} 个文件`);
    closeCreateSystemKbModal();
  } catch (err) {
    showToastMessage(`创建失败: ${err.message}`, 'error');
    console.log(`创建失败: ${err.message}`, 'error')
  } finally {
    uploading.value = false;
    progress.value = 0;
  }
};

/**
 * 上传文件到个人知识库
 */
const handleUploadFile = async () => {
  if (!selectedKb.value || !fileToUpload.value) return;
  if (!email) {
    showToastMessage('用户未登录，无法上传文件', 'error');
    return;
  }

  uploading.value = true;
  progress.value = 0;

  try {
    const formData = new FormData();
    formData.append('kbId', selectedKb.value.id);
    formData.append('file', fileToUpload.value);
    formData.append('email', email);

    const uploadedFile = await uploadFileToKbService(formData, (e) => {
      if (e.lengthComputable) {
        progress.value = Math.round((e.loaded / e.total) * 100);
      }
    });

    const index = userKnowledgeBases.value.findIndex(kb => kb.id === selectedKb.value.id);
    if (index !== -1) {
      const fileItem = {
        id: uploadedFile.id,
        name: uploadedFile.name,
        size: uploadedFile.size,
        uploadedAt: uploadedFile.created_at,
        type: uploadedFile.type
      };
      if (!userKnowledgeBases.value[index].files) userKnowledgeBases.value[index].files = [];
      userKnowledgeBases.value[index].files.push(fileItem);
      userKnowledgeBases.value[index].docCount++;
      selectedKb.value.files = [...userKnowledgeBases.value[index].files];
      selectedKb.value.docCount = userKnowledgeBases.value[index].docCount;
    }

    showToastMessage(`文件已成功上传到 ${selectedKb.value.name}`);
    closeUploadFileModal();
  } catch (err) {
    showToastMessage(`上传失败: ${err.message}`, 'error');
    console.error('上传文件错误:', err);
  } finally {
    uploading.value = false;
    progress.value = 0;
    if (uploadFileInput.value) uploadFileInput.value.value = '';
  }
};

/**
 * 管理员上传文件到系统知识库
 */
const handleSystemUploadFile = async () => {
  if (!selectedSystemKb.value || !fileToUpload.value) return;
  if (!isAdmin) {
    showToastMessage('非管理员无权限操作', 'error');
    return;
  }

  uploading.value = true;
  progress.value = 0;

  try {
    const formData = new FormData();
    formData.append('systemKbId', selectedSystemKb.value.id);
    formData.append('file', fileToUpload.value);
    formData.append('email', email);

    const uploadedFile = await uploadFileToSystemKbService(formData, (e) => {
      if (e.lengthComputable) progress.value = Math.round((e.loaded / e.total) * 100);
    });

    const fileItem = {
      id: uploadedFile.id,
      name: uploadedFile.name,
      size: uploadedFile.size,
      uploadedAt: uploadedFile.created_at,
      type: uploadedFile.type
    };
    if (!selectedSystemKb.value.files) selectedSystemKb.value.files = [];
    selectedSystemKb.value.files.push(fileItem);
    
    const systemKbIndex = systemKnowledgeBases.value.findIndex(kb => kb.id === selectedSystemKb.value.id);
    if (systemKbIndex !== -1) {
      systemKnowledgeBases.value[systemKbIndex].docCount++;
      systemKnowledgeBases.value[systemKbIndex].files = [...selectedSystemKb.value.files];
    }

    showToastMessage(`文件已成功上传到 ${selectedSystemKb.value.name}`);
    closeSystemUploadFileModal();
  } catch (err) {
    showToastMessage(`上传失败: ${err.message}`, 'error');
  } finally {
    uploading.value = false;
    progress.value = 0;
  }
};

/**
 * 删除个人知识库文件
 */
const deleteFile = async (fileId) => {
  if (!confirm('确定要删除这个文件吗？此操作不可恢复。')) return;
  if (!email || !selectedKb.value) {
    showToastMessage('用户未登录或知识库不存在', 'error');
    return;
  }

  try {
    await deleteKbFileService({
      kbId: selectedKb.value.id,
      fileId,
      email
    });

    const kbIndex = userKnowledgeBases.value.findIndex(kb => kb.id === selectedKb.value.id);
    if (kbIndex !== -1) {
      const fileIndex = userKnowledgeBases.value[kbIndex].files.findIndex(file => file.id === fileId);
      if (fileIndex !== -1) {
        userKnowledgeBases.value[kbIndex].files.splice(fileIndex, 1);
        userKnowledgeBases.value[kbIndex].docCount--;
        selectedKb.value.files = [...userKnowledgeBases.value[kbIndex].files];
        selectedKb.value.docCount = userKnowledgeBases.value[kbIndex].docCount;
      }
    }

    showToastMessage('文件删除成功');
  } catch (err) {
    showToastMessage(`删除失败: ${err.message}`, 'error');
    console.error('删除文件错误:', err);
  }
};

/**
 * 管理员删除系统知识库文件
 */
const deleteSystemKbFile = async (fileId) => {
  if (!confirm('确定要删除这个系统知识库文件吗？此操作不可恢复。')) return;
  if (!isAdmin || !selectedSystemKb.value) {
    showToastMessage('非管理员无权限操作或系统知识库不存在', 'error');
    return;
  }

  try {
    await deleteSystemKbFileService({
      systemKbId: selectedSystemKb.value.id,
      fileId,
      email
    });

    const fileIndex = selectedSystemKb.value.files.findIndex(file => file.id === fileId);
    if (fileIndex !== -1) {
      selectedSystemKb.value.files.splice(fileIndex, 1);
      
      const systemKbIndex = systemKnowledgeBases.value.findIndex(kb => kb.id === selectedSystemKb.value.id);
      if (systemKbIndex !== -1) {
        systemKnowledgeBases.value[systemKbIndex].docCount--;
        systemKnowledgeBases.value[systemKbIndex].files = [...selectedSystemKb.value.files];
      }
    }

    showToastMessage('系统知识库文件删除成功');
  } catch (err) {
    showToastMessage(`删除失败: ${err.message}`, 'error');
  }
};

/**
 * 删除个人知识库
 */
const deleteKnowledgeBase = async (index) => {
  const kb = userKnowledgeBases.value[index];
  if (!confirm(`确定要删除"${kb.name}"吗？此操作不可恢复。`)) return;
  if (!email) {
    showToastMessage('用户未登录，无法删除知识库', 'error');
    return;
  }

  try {
    await deleteKnowledgeBaseService({
      kbId: kb.id,
      email
    });

    if (selectedKb.value && selectedKb.value.id === kb.id) {
      selectedKb.value = null;
    }
    userKnowledgeBases.value.splice(index, 1);
    showToastMessage('知识库删除成功');
  } catch (err) {
    showToastMessage(`删除失败: ${err.message}`, 'error');
    console.error('删除知识库错误:', err);
  }
};

/**
 * 管理员删除系统知识库
 */
const deleteSystemKnowledgeBase = async (index) => {
  const systemKb = systemKnowledgeBases.value[index];
  if (!confirm(`确定要删除系统知识库"${systemKb.name}"吗？此操作不可恢复。`)) return;
  if (!isAdmin) {
    showToastMessage('非管理员无权限操作', 'error');
    return;
  }

  try {
    await deleteSystemKnowledgeBaseService({
      systemKbId: systemKb.id,
      email
    });

    if (selectedSystemKb.value && selectedSystemKb.value.id === systemKb.id) {
      selectedSystemKb.value = null;
    }
    systemKnowledgeBases.value.splice(index, 1);
    showToastMessage('系统知识库删除成功');
  } catch (err) {
    showToastMessage(`删除失败: ${err.message}`, 'error');
  }
};

/**
 * 格式化文件大小
 */
const formatSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

/**
 * 取消选择知识库
 */
const deselectKnowledgeBase = async () => {
  if (!selectedKb.value || isNaN(numericId)) {
    showToastMessage('机器人ID无效或未选择知识库', 'error');
    return;
  }

  try {
    await deselectKbService({ robotId: numericId });
    selectedKb.value = null;
    showToastMessage('取消选择成功');
  } catch (err) {
    showToastMessage(`取消失败: ${err.message}`, 'error');
    console.error('取消知识库错误:', err);
  }
};

/**
 * 返回主页面
 */
const back = () => {
  router.push("/main");
};

/**
 * 页面挂载初始化
 */
onMounted(() => {
  fetchInitialData();
});
</script>

<template>
  <div class="w-screen h-screen">
    <!-- 提示框组件 -->
    <div v-if="showToast"
      class="fixed top-4 right-[40%]  px-6 py-3 rounded-lg shadow-lg z-50 transition-all duration-300 transform translate-y-0 opacity-100"
      :class="toastType === 'success' ? 'bg-green-100 text-green-800 border border-green-200' : 'bg-red-100 text-red-800 border border-red-200'">
      <p class="flex items-center">
        <i :class="toastType === 'success' ? 'fas fa-check-circle mr-2' : 'fas fa-exclamation-circle mr-2'"></i>
        {{ toastMessage }}
      </p>
    </div>

    <div class="min-h-screen  dark:bg-gray-900 text-gray-900 dark:text-gray-100 flex flex-col">
      <!-- 页面头部 -->
      <header
        class="w-[86%] ml-[7%] rounded-b bg-white/85 dark:bg-gray-800 shadow-sm border-b border-gray-200 dark:border-gray-700">
        <div
          class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3 flex flex-col sm:flex-row justify-between items-start sm:items-center">
          <div>
            <h1 class="text-2xl font-bold">知识库管理</h1>
            <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">选择一个知识库进行管理</p>
            <div v-if="!isNaN(numericId)" class="mt-2 text-sm text-gray-500">
              机器人ID: {{ numericId }}
            </div>
          </div>

          <!-- 管理员按钮 -->
          <button 
            v-if="isAdmin" 
            @click="openCreateSystemKbModal"
            class="mr-4 flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg shadow transition-all duration-300 transform hover:scale-105"
          >
            <i class="fas fa-plus mr-2"></i> +新增系统知识库
          </button>

          <!-- 取消选择知识库按钮 -->
          <button v-if="selectedKb" @click="deselectKnowledgeBase"
            class="mt-4 ml-[-100%] sm:mt-0 px-4 py-2 bg-slate-100 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200 rounded-lg shadow-sm transition-colors flex items-center self-end sm:self-auto">
            <i class="fas fa-times mr-2"></i>
            取消当前选择
          </button>

          <button @click="back"
            class="flex items-center px-4 pl-2 py-2 bg-red-500 hover:bg-red-700 text-white rounded-lg shadow transition-all duration-300 transform hover:scale-105">
            <i class="fas fa-plus mr-2"></i> 返回
          </button>
        </div>
      </header>

      <!-- 主要内容区 -->
      <main class="w-[85%] flex-1 max-w-9xl  mx-auto px-4 sm:px-6 lg:px-8 py-8 bg-slate-400/50 rounded-2xl m-5">
        <!-- 加载状态 -->
        <div v-if="loading" class="text-center py-10">
          <div class="inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
          <p class="mt-4 text-gray-100">加载知识库数据中...</p>
        </div>

        <!-- 错误状态 -->
        <div v-if="error && !loading"
          class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mb-6">
          <p class="text-red-700 dark:text-red-300 flex items-center">
            <i class="fas fa-exclamation-circle mr-2"></i> {{ error }}
          </p>
          <button @click="fetchInitialData" class="mt-2 text-sm text-blue-600 dark:text-blue-400 hover:underline">
            重试
          </button>
        </div>

        <!-- 内容区域 -->
        <div v-if="!loading && !error">
          <!-- 系统自带知识库 -->
          <section class="mb-10">
            <h2 class="text-xl font-semibold mb-4 flex items-center ">
              <i class="fas fa-server text-blue-500 mr-2"></i>系统知识库
              <span class="ml-2 text-sm font-normal text-gray-300">
                {{ isAdmin ? '（管理员可操作：查看/上传/删除）' : '（仅可选择，不可查看文件）' }}
              </span>
            </h2>

            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
              <div v-for="(kb, index) in systemKnowledgeBases" :key="kb.id"
                class="bg-white dark:bg-gray-800 rounded-lg shadow-md hover:shadow-lg transition-all duration-300 border border-gray-200 dark:border-gray-700 overflow-hidden cursor-pointer relative"
                :class="selectedKb?.id === kb.id && !selectedKb?.isUserKb ? 'ring-2 ring-red-500 dark:ring-blue-400' : ''"
                @click="selectKnowledgeBase(kb)">
                <div class="p-5">
                  <div class="flex justify-between items-start">
                    <h3 class="font-medium text-lg">{{ kb.name }}</h3>
                  </div>
                  <p class="mt-2 text-sm text-gray-600 dark:text-gray-400 line-clamp-2">
                    {{ kb.description }}
                  </p>
                  <div class="mt-4 flex items-center text-sm text-gray-500 dark:text-gray-500">
                    <span class="flex items-center mr-4">
                      <i class="fas fa-file-alt mr-1"></i> {{ kb.docCount }} 文档
                    </span>
                    <span class="flex items-center">
                      <i class="fas fa-sync-alt mr-1"></i> {{ formatDate(kb.created_at) }}
                    </span>
                  </div>
                </div>

                <!-- 管理员操作按钮 -->
                <div v-if="isAdmin" class="absolute top-2 right-2 flex flex-col gap-2">
                  <button @click.stop="openSystemFileListModal(kb)"
                    class="bg-blue-500 text-white rounded-full w-7 h-7 flex items-center justify-center hover:bg-blue-600 shadow-md"
                    aria-label="查看系统知识库文件">
                    <File class="w-4 h-4"></File>
                  </button>
                  <button @click.stop="deleteSystemKnowledgeBase(index)"
                    class="bg-red-500 text-white rounded-full w-7 h-7 flex items-center justify-center hover:bg-red-600 shadow-md"
                    aria-label="删除系统知识库">
                    <Trash2 class="w-4 h-4"></Trash2>
                  </button>
                </div>
              </div>
            </div>
          </section>

          <!-- 分隔线 -->
          <div class="relative my-8">
            <div class="absolute inset-0 flex items-center">
              <div class="w-full border-t border-gray-300 dark:border-gray-700"></div>
            </div>
            <div class="relative flex justify-center">
              <span class="px-3 bg-gray-50 dark:bg-gray-900 text-sm text-gray-500 dark:text-gray-500">
                我的知识库
              </span>
            </div>
          </div>

          <!-- 用户上传的知识库 -->
          <section>
            <div class="flex justify-between items-center mb-4">
              <h2 class="text-xl font-semibold flex items-center">
                <i class="fas fa-user-folder text-green-500 mr-2"></i>个人知识库
              </h2>

              <button @click="openCreateModal"
                class="flex items-center px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg shadow transition-all duration-300 transform hover:scale-105">
                <i class="fas fa-plus mr-2"></i> +新建知识库
              </button>
            </div>

            <!-- 用户知识库列表 -->
            <div v-if="userKnowledgeBases.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
              <div v-for="(kb, index) in userKnowledgeBases" :key="kb.id"
                class="bg-white dark:bg-gray-800 rounded-lg shadow-md hover:shadow-lg transition-all duration-300 border border-gray-200 dark:border-gray-700 overflow-hidden group cursor-pointer relative"
                :class="selectedKb?.id === kb.id && selectedKb?.isUserKb ? 'ring-2 ring-green-500 dark:ring-green-400' : ''"
                @click="selectKnowledgeBase(kb, true)">
                <!-- 文件列表按钮 -->
                <button @click.stop="openFileListModal(kb)"
                  class="absolute top-2 right-2 bg-blue-500 text-white rounded-full w-7 h-7 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-300 hover:bg-blue-600 shadow-md transform translate-y-2 group-hover:translate-y-0"
                  aria-label="查看文件列表">
                  <File class="w-4 h-4"></File>
                </button>

                <!-- 删除按钮 -->
                <button @click.stop="deleteKnowledgeBase(index)"
                  class="absolute top-2 right-10 bg-red-500 text-white rounded-full w-7 h-7 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-300 hover:bg-red-600 shadow-md transform translate-y-2 group-hover:translate-y-0"
                  aria-label="删除知识库">
                  <Trash2 class="w-4 h-4"></Trash2>
                </button>

                <div class="p-5 w-[100%]">
                  <h3 class="font-medium text-lg bg-slate-200 pl-2 rounded w-[40%] flex">
                    <Book class="w-5 h-5 mt-1 mr-1 text-blue-600"></Book>{{ kb.name }}
                  </h3>
                  <p
                    class="mt-2 text-sm text-gray-600 dark:text-gray-400 line-clamp-2   overflow-hidden whitespace-nowrap text-overflow-ellipsis">
                    {{ kb.description || '无描述' }}
                  </p>
                  <div class="mt-4 flex items-center text-sm text-gray-500 dark:text-gray-500 ">
                    <span class="flex items-center mr-4 ">
                      <i class="fas fa-file-alt mr-1"></i> {{ kb.docCount }} 文档
                    </span>
                    <span class="flex items-center ">
                      <i class="fas fa-upload mr-1"></i> {{ formatDate(kb.uploadedAt || kb.created_at) }}
                    </span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-else
              class="bg-white/70 dark:bg-gray-800 rounded-lg border border-dashed border-gray-300 dark:border-gray-700 p-2 text-center">
            
              <h3 class="text-lg font-medium mb-2">暂无个人知识库</h3>
              <p class="text-gray-500 dark:text-gray-400 mb-6">您可以创建自己的知识库并上传文件进行管理</p>
              <button @click="openCreateModal"
                class="inline-flex items-center px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg shadow transition-all duration-300">
                <i class="fas fa-plus mr-2"></i> 创建第一个知识库
              </button>
            </div>
          </section>
        </div>
      </main>


      <!-- 创建个人知识库模态框 -->
      <div v-if="isCreateModalOpen"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
        @click="closeModalOnOutside($event, 'create')">
        <div
          class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl transform transition-all duration-300 animate-fadeIn"
          @click.stop>
          <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
            <h3 class="text-lg font-medium">创建知识库</h3>
            <button @click="closeCreateModal" class="text-gray-400 hover:text-gray-500 focus:outline-none"
              aria-label="关闭">
              <i class="fas fa-times"></i>
            </button>
          </div>

          <div class="px-6 py-5">
            <form @submit.prevent="handleCreateKb">
              <div class="mb-4">
                <label for="kbName" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  知识库名称 <span class="text-red-500">*</span>
                </label>
                <input type="text" id="kbName" v-model="kbName"
                  class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-green-500 dark:bg-gray-700 dark:text-white transition-colors"
                  placeholder="请输入知识库名称" required>
              </div>

              <div class="mb-5">
                <label for="kbDescription" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  知识库描述 <span class="text-red-500">*</span>
                </label>
                <textarea id="kbDescription" v-model="kbDescription" rows="3"
                  class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-green-500 dark:bg-gray-700 dark:text-white transition-colors"
                  placeholder="请输入知识库描述" required></textarea>
              </div>

              <!-- 创建时上传文件 -->
              <div class="mb-5">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  上传初始文件
                </label>
                <div
                  class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 dark:border-gray-600 border-dashed rounded-md hover:border-blue-300 dark:hover:border-blue-700 transition-colors">
                  <div class="space-y-1 text-center">
                    <i class="fas fa-file text-3xl text-gray-400"></i>
                    <div class="flex text-sm text-gray-600 dark:text-gray-400">
                      <label for="createFileInput"
                        class="relative cursor-pointer bg-white rounded-md font-medium text-blue-600 hover:text-blue-500 focus-within:outline-none">
                        <span>选择文件</span>
                        <input ref="createFileInput" id="createFileInput" type="file" multiple class="sr-only"
                          @change="handleCreateFileSelection">
                      </label>
                      <p class="pl-1">或拖放文件到此处</p>
                    </div>
                    <p class="text-xs text-gray-500 dark:text-gray-500">
                      支持 PDF, DOCX, TXT, MD 等格式文件
                    </p>
                  </div>
                </div>

                <!-- 已选择文件显示 -->
                <div v-if="selectedFilesToUpload.length > 0" class="mt-3">
                  <p class="text-sm font-medium mb-1">已选择 {{ selectedFilesToUpload.length }} 个文件:</p>
                  <div class="text-sm max-h-32 overflow-y-auto pr-2">
                    <div v-for="(file, idx) in selectedFilesToUpload" :key="idx" class="flex items-center mb-1">
                      <i class="fas fa-file text-gray-500 mr-2"></i>
                      <span class="truncate flex-1">{{ file.name }} ({{ formatSize(file.size) }})</span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 进度条 -->
              <div v-if="uploading" class="mb-4">
                <p>处理中: {{ progress }}%</p>
                <div class="w-full bg-gray-200 rounded-full h-2.5">
                  <div class="bg-blue-600 h-2.5 rounded-full" :style="{ width: progress + '%' }"></div>
                </div>
              </div>

              <div class="flex justify-end space-x-3">
                <button type="button" @click="closeCreateModal"
                  class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors">
                  取消
                </button>
                <button type="submit" :disabled="!isCreateFormValid"
                  class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
                  创建知识库
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- 个人知识库文件列表模态框 -->
      <div v-if="isFileListModalOpen && selectedKb"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
        @click="closeModalOnOutside($event, 'fileList')">
        <div
          class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl transform transition-all duration-300 animate-fadeIn"
          @click.stop>
          <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
            <h3 class="text-lg font-medium">{{ selectedKb.name }} 的文件列表</h3>
            <div class="flex items-center">
              <!-- 上传文件按钮 -->
              <button @click="openUploadFileModal"
                class="mr-3 px-3 py-1 bg-blue-600 hover:bg-blue-700 text-white rounded-md text-sm transition-colors">
                <i class="fas fa-upload mr-1"></i> 上传文件
              </button>
              <button @click="closeFileListModal" class="text-gray-400 hover:text-gray-500 focus:outline-none"
                aria-label="关闭">
                <i class="fas fa-times"></i>
              </button>
            </div>
          </div>

          <div class="px-6 py-5 max-h-[70vh] overflow-y-auto">
            <!-- 知识库描述 -->
            <div class="mb-4 p-3 bg-gray-50 dark:bg-gray-700 rounded-md">
              <p class="text-sm text-gray-600 dark:text-gray-300">
                {{ selectedKb.description }}
              </p>
            </div>

            <!-- 文件列表 -->
            <div v-if="selectedKb.files && selectedKb.files.length > 0" class="space-y-3">
              <div class="flex items-center font-medium text-gray-700 dark:text-gray-300 border-b pb-2">
                <div class="w-1/2">文件名</div>
                <div class="w-1/6 text-center">大小</div>
                <div class="w-1/6 text-center">上传日期</div>
                <div class="w-1/6 text-center">操作</div>
              </div>

              <div v-for="file in selectedKb.files" :key="file.id"
                class="flex items-center p-2 hover:bg-gray-50 dark:hover:bg-gray-700 rounded-md">
                <div class="w-1/2 truncate">
                  <i class="fas fa-file mr-2 text-gray-500"></i>
                  {{ file.name }}
                </div>
                <div class="w-1/6 text-center text-sm">
                  {{ formatSize(file.size) }}
                </div>
                <div class="w-1/6 text-center text-sm">
                  {{ formatDate(file.uploadedAt) }}
                </div>
                <div class="w-1/6 text-center">
                  <button @click="deleteFile(file.id)" class="text-red-500 hover:text-red-700 transition-colors"
                    aria-label="删除">
                    <i class="fas fa-trash">删除</i>
                  </button>
                </div>
              </div>
            </div>

            <!-- 空文件状态 -->
            <div v-else class="text-center py-10">
              <div
                class="w-16 h-16 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center mx-auto mb-4">
                <i class="fas fa-file-alt text-2xl text-gray-400"></i>
              </div>
              <h3 class="text-lg font-medium mb-2">该知识库暂无文件</h3>
              <p class="text-gray-500 dark:text-gray-400 mb-6">
                点击"上传文件"按钮添加文件
              </p>
            </div>
          </div>
        </div>
      </div>

      <!-- 个人知识库上传文件模态框 -->
      <div v-if="isUploadFileModalOpen && selectedKb"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
        @click="closeModalOnOutside($event, 'uploadFile')">
        <div
          class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md transform transition-all duration-300 animate-fadeIn"
          @click.stop>
          <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
            <h3 class="text-lg font-medium">上传文件到 {{ selectedKb.name }}</h3>
            <button @click="closeUploadFileModal" class="text-gray-400 hover:text-gray-500 focus:outline-none"
              aria-label="关闭">
              <i class="fas fa-times"></i>
            </button>
          </div>

          <div class="px-6 py-5">
            <form @submit.prevent="handleUploadFile">
              <div class="mb-5">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  选择文件 <span class="text-red-500">*</span>
                </label>
                <div
                  class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 dark:border-gray-600 border-dashed rounded-md hover:border-blue-300 dark:hover:border-blue-700 transition-colors">
                  <div class="space-y-1 text-center">
                    <i class="fas fa-file text-3xl text-gray-400"></i>
                    <div class="flex text-sm text-gray-600 dark:text-gray-400">
                      <label for="uploadFileInput"
                        class="relative cursor-pointer bg-white rounded-md font-medium text-blue-600 hover:text-blue-500 focus-within:outline-none">
                        <span>选择文件</span>
                        <input ref="uploadFileInput" id="uploadFileInput" type="file" class="sr-only"
                          @change="handleUploadFileSelection">
                      </label>
                      <p class="pl-1">或拖放文件到此处</p>
                    </div>
                    <p class="text-xs text-gray-500 dark:text-gray-500">
                      支持 PDF, DOCX, TXT, MD 等格式文件
                    </p>
                  </div>
                </div>

                <!-- 已选择文件显示 -->
                <div v-if="fileToUpload" class="mt-3">
                  <p class="text-sm font-medium mb-1">已选择文件:</p>
                  <div class="text-sm flex items-center">
                    <i class="fas fa-file text-gray-500 mr-2"></i>
                    <span class="truncate flex-1">{{ fileToUpload.name }} ({{ formatSize(fileToUpload.size) }})</span>
                  </div>
                </div>
              </div>

              <!-- 上传进度 -->
              <div v-if="uploading" class="mb-4">
                <p>上传中: {{ progress }}%</p>
                <div class="w-full bg-gray-200 rounded-full h-2.5">
                  <div class="bg-blue-600 h-2.5 rounded-full" :style="{ width: progress + '%' }"></div>
                </div>
              </div>

              <div class="flex justify-end space-x-3">
                <button type="button" @click="closeUploadFileModal"
                  class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors">
                  取消
                </button>
                <button type="submit" :disabled="!isUploadFormValid"
                  class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
                  上传文件
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- 管理员：创建系统知识库模态框 -->
      <div v-if="isCreateSystemKbModalOpen"
        class="fixed inset-0 bg-slate-300/75 bg-opacity-50 flex items-center justify-center z-50 p-4"
        @click="closeModalOnOutside($event, 'createSystem')">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl transform transition-all duration-300 animate-fadeIn"
          @click.stop>
          <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
            <h3 class="text-lg font-medium">创建系统知识库（管理员专属）</h3>
            <button @click="closeCreateSystemKbModal" class="text-gray-400 hover:text-gray-500 focus:outline-none"
              aria-label="关闭">
              <i class="fas fa-times"></i>
            </button>
          </div>
          <div class="px-6 py-5">
            <form @submit.prevent="handleCreateSystemKb">
              <div class="mb-4">
                <label for="systemKbName" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  系统知识库名称 <span class="text-red-500">*</span>
                </label>
                <input type="text" id="systemKbName" v-model="kbName"
                  class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white transition-colors"
                  placeholder="请输入系统知识库名称" required>
              </div>
              <div class="mb-5">
                <label for="systemKbDescription" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  系统知识库描述 <span class="text-red-500">*</span>
                </label>
                <textarea id="systemKbDescription" v-model="kbDescription" rows="3"
                  class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white transition-colors"
                  placeholder="请输入系统知识库描述" required></textarea>
              </div>
              <div class="mb-5">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  上传初始文件 <span class="text-red-500">*</span>
                </label>
                <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 dark:border-gray-600 border-dashed rounded-md hover:border-blue-300 dark:hover:border-blue-700 transition-colors">
                  <div class="space-y-1 text-center">
                    <i class="fas fa-file text-3xl text-gray-400"></i>
                    <div class="flex text-sm text-gray-600 dark:text-gray-400">
                      <label for="createSystemFileInput"
                        class="relative cursor-pointer bg-white rounded-md font-medium text-blue-600 hover:text-blue-500 focus-within:outline-none">
                        <span>选择文件</span>
                        <input ref="createFileInput" id="createSystemFileInput" type="file" multiple class="sr-only"
                          @change="handleCreateFileSelection">
                      </label>
                      <p class="pl-1">或拖放文件到此处</p>
                    </div>
                    <p class="text-xs text-gray-500 dark:text-gray-500">
                      支持 PDF, DOCX, TXT, MD 等格式文件
                    </p>
                  </div>
                </div>
                <div v-if="selectedFilesToUpload.length > 0" class="mt-3">
                  <p class="text-sm font-medium mb-1">已选择 {{ selectedFilesToUpload.length }} 个文件:</p>
                  <div class="text-sm max-h-32 overflow-y-auto pr-2">
                    <div v-for="(file, idx) in selectedFilesToUpload" :key="idx" class="flex items-center mb-1">
                      <i class="fas fa-file text-gray-500 mr-2"></i>
                      <span class="truncate flex-1">{{ file.name }} ({{ formatSize(file.size) }})</span>
                    </div>
                  </div>
                </div>
              </div>
              <div v-if="uploading" class="mb-4">
                <p>处理中: {{ progress }}%</p>
                <div class="w-full bg-gray-200 rounded-full h-2.5">
                  <div class="bg-blue-600 h-2.5 rounded-full" :style="{ width: progress + '%' }"></div>
                </div>
              </div>
              <div class="flex justify-end space-x-3">
                <button type="button" @click="closeCreateSystemKbModal"
                  class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors">
                  取消
                </button>
                <button type="submit" :disabled="!isCreateFormValid"
                  class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
                  创建系统知识库
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- 管理员：系统知识库文件列表模态框 -->
      <div v-if="isSystemFileListModalOpen && selectedSystemKb"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
        @click="closeModalOnOutside($event, 'systemFileList')">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl transform transition-all duration-300 animate-fadeIn"
          @click.stop>
          <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
            <h3 class="text-lg font-medium">{{ selectedSystemKb.name }} 的文件列表（系统知识库）</h3>
            <div class="flex items-center">
              <button @click="openSystemUploadFileModal"
                class="mr-3 px-3 py-1 bg-blue-600 hover:bg-blue-700 text-white rounded-md text-sm transition-colors">
                <i class="fas fa-upload mr-1"></i> 上传文件
              </button>
              <button @click="closeSystemFileListModal" class="text-gray-400 hover:text-gray-500 focus:outline-none"
                aria-label="关闭">
                <i class="fas fa-times"></i>
              </button>
            </div>
          </div>
          <div class="px-6 py-5 max-h-[70vh] overflow-y-auto">
            <div class="mb-4 p-3 bg-gray-50 dark:bg-gray-700 rounded-md">
              <p class="text-sm text-gray-600 dark:text-gray-300">
                {{ selectedSystemKb.description }}
              </p>
            </div>
            <div v-if="selectedSystemKb.files && selectedSystemKb.files.length > 0" class="space-y-3">
              <div class="flex items-center font-medium text-gray-700 dark:text-gray-300 border-b pb-2">
                <div class="w-1/2">文件名</div>
                <div class="w-1/6 text-center">大小</div>
                <div class="w-1/6 text-center">上传日期</div>
                <div class="w-1/6 text-center">操作</div>
              </div>
              <div v-for="file in selectedSystemKb.files" :key="file.id"
                class="flex items-center p-2 hover:bg-gray-50 dark:hover:bg-gray-700 rounded-md">
                <div class="w-1/2 truncate">
                  <i class="fas fa-file mr-2 text-gray-500"></i>
                  {{ file.name }}
                </div>
                <div class="w-1/6 text-center text-sm">
                  {{ formatSize(file.size) }}
                </div>
                <div class="w-1/6 text-center text-sm">
                  {{ formatDate(file.uploadedAt) }}
                </div>
                <div class="w-1/6 text-center">
                  <button @click="deleteSystemKbFile(file.id)" class="text-red-500 hover:text-red-700 transition-colors"
                    aria-label="删除">
                    <i class="fas fa-trash">删除</i>
                  </button>
                </div>
              </div>
            </div>
            <div v-else class="text-center py-10">
              <div
                class="w-16 h-16 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center mx-auto mb-4">
                <i class="fas fa-file-alt text-2xl text-gray-400"></i>
              </div>
              <h3 class="text-lg font-medium mb-2">该系统知识库暂无文件</h3>
              <p class="text-gray-500 dark:text-gray-400 mb-6">
                点击"上传文件"按钮添加文件
              </p>
            </div>
          </div>
        </div>
      </div>

      <!-- 管理员：系统知识库上传文件模态框 -->
      <div v-if="isSystemUploadFileModalOpen && selectedSystemKb"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
        @click="closeModalOnOutside($event, 'systemUploadFile')">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md transform transition-all duration-300 animate-fadeIn"
          @click.stop>
          <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
            <h3 class="text-lg font-medium">上传文件到 {{ selectedSystemKb.name }}（系统知识库）</h3>
            <button @click="closeSystemUploadFileModal" class="text-gray-400 hover:text-gray-500 focus:outline-none"
              aria-label="关闭">
              <i class="fas fa-times"></i>
            </button>
          </div>
          <div class="px-6 py-5">
            <form @submit.prevent="handleSystemUploadFile">
              <div class="mb-5">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  选择文件 <span class="text-red-500">*</span>
                </label>
                <div
                  class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 dark:border-gray-600 border-dashed rounded-md hover:border-blue-300 dark:hover:border-blue-700 transition-colors">
                  <div class="space-y-1 text-center">
                    <i class="fas fa-file text-3xl text-gray-400"></i>
                    <div class="flex text-sm text-gray-600 dark:text-gray-400">
                      <label for="systemUploadFileInput"
                        class="relative cursor-pointer bg-white rounded-md font-medium text-blue-600 hover:text-blue-500 focus-within:outline-none">
                        <span>选择文件</span>
                        <input ref="uploadFileInput" id="systemUploadFileInput" type="file" class="sr-only"
                          @change="handleUploadFileSelection">
                      </label>
                      <p class="pl-1">或拖放文件到此处</p>
                    </div>
                    <p class="text-xs text-gray-500 dark:text-gray-500">
                      支持 PDF, DOCX, TXT, MD 等格式文件
                    </p>
                  </div>
                </div>
                <div v-if="fileToUpload" class="mt-3">
                  <p class="text-sm font-medium mb-1">已选择文件:</p>
                  <div class="text-sm flex items-center">
                    <i class="fas fa-file text-gray-500 mr-2"></i>
                    <span class="truncate flex-1">{{ fileToUpload.name }} ({{ formatSize(fileToUpload.size) }})</span>
                  </div>
                </div>
              </div>
              <div v-if="uploading" class="mb-4">
                <p>上传中: {{ progress }}%</p>
                <div class="w-full bg-gray-200 rounded-full h-2.5">
                  <div class="bg-blue-600 h-2.5 rounded-full" :style="{ width: progress + '%' }"></div>
                </div>
              </div>
              <div class="flex justify-end space-x-3">
                <button type="button" @click="closeSystemUploadFileModal"
                  class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors">
                  取消
                </button>
                <button type="submit" :disabled="!isUploadFormValid"
                  class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
                  上传文件
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 自定义动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fadeIn {
  animation: fadeIn 0.3s ease-out forwards;
}

/* 加载动画 */
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}
</style>
